class Ad {
    constructor(options) {
        this.options = Object.assign(
            {
                time: 10,
            },
            options)
        
        this.el=document.querySelector(this.options.el);
        this.el.style.position="fixed"
        this.x=this.y=1
        
        this.intervalId=setInterval(this.run.bind(this),this.options.time)
        this.bindEvent()
        close=document.createElement('div')
        close.style.cssText=`
            width:20px;
            height:20px;
            position:absolute;
            right:0;
            top:0;
            background-color:black;
            color:white;
            text-align:center
        `
        close.innerText='x'
        this.el.insertAdjacentElement('beforeEnd',close)
        close.addEventListener('click',()=>{
            this.el.style.visibility='hidden'
        })
    }

    bindEvent() {
        this.el.addEventListener("mouseover", () => {
            clearInterval(this.intervalId);
            this.el.style.cursor="pointer"
        });
        this.el.addEventListener("mouseout", () => {
            this.intervalId=setInterval(this.run.bind(this),this.options.time)
        });
      }


    // 定时器执行函数
    run() {
        this.el.style.left = this.left() + "px";
        this.el.style.top = this.top() + "px";
    }

    left() {
        const { x, width } = this.el.getBoundingClientRect();
        const { clientWidth } = document.documentElement;
        if (x + width > clientWidth) this.x = -1;
        if (x < 0) this.x = 1;
        return x + this.x;
    }

    top() {
        const { y, height } = this.el.getBoundingClientRect();
        const { clientHeight } = document.documentElement;

        if (y + height > clientHeight) this.y = -1;
        if (y < 0) this.y = 1;

        return y + this.y;
    }
}

let fun=(options)=>new Ad(options)
export {fun}